package cn.duxiaod.demo.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获取TargetObject类的class对象并且创建实例
        Class<?> tagetClass = Class.forName("cn.duxiaod.demo.reflection.TagetObject");
        TagetObject tagetObject = (TagetObject) tagetClass.newInstance();
        System.out.println("---------------------");
        //获取类中所有定义的方法
        Method[] declaredMethods = tagetClass.getDeclaredMethods();
        for (Method method:declaredMethods) {
            System.out.println(method.getName());
        }
        System.out.println("---------------------");
        //获取指定方法并执行
        Method publicMethod = tagetClass.getDeclaredMethod("publicMethod", String.class);
        publicMethod.invoke(tagetObject,"publicMethod");
        System.out.println("---------------------");

        //获取指定参数并修改
        Field field = tagetClass.getDeclaredField("value");
        //为了对类的参数进行修改取消安全检查（否则会报错：java.lang.IllegalAccessException）
        field.setAccessible(true);
        field.set(tagetObject,"Lisi");

        //调用private方法
        Method privateMethod = tagetClass.getDeclaredMethod("privateMethod");
        //为了对类的私有方法进行修改取消安全检查（否则会报错：java.lang.IllegalAccessException）
        privateMethod.setAccessible(true);
        privateMethod.invoke(tagetObject);
    }
}
